package xmlwriter;

import java.io.File;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import sun.util.calendar.*;

import bandi.osgi.gpsdata.ClientMessage;
import bandi.osgi.gpsdata.GpsGGAMessage;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

import bandi.osgi.dal.dao.beans.*;
import bandi.osgi.dal.dao.devices.impl.*;

public class XMLCreatorExample {
	private Document dom,dom2;
	public Element rootEle,rootEle2;
	public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
	private Comment comment;
	public XMLCreatorExample() throws SQLException, ClassNotFoundException {
		createDocument();
		    rootEle = dom.createElement("rdf:RDF");
			rootEle.setAttribute("xmlns:rdf",
					"http://www.w3.org/1999/02/22-rdf-syntax-ns#");
			rootEle.setAttribute("xmlns", "http://purl.org/rss/1.0/");
			rootEle.setAttribute("xmlns:dc", "http://purl.org/dc/elements/1.1/");
			rootEle.setAttribute("xmlns:georss", "http://www.georss.org/georss");			
			dom.appendChild(rootEle);
			printToFile(dom);
			
			rootEle2 = dom2.createElement("rdf:RDF");
			rootEle2.setAttribute("xmlns:rdf",
					"http://www.w3.org/1999/02/22-rdf-syntax-ns#");
			rootEle2.setAttribute("xmlns", "http://purl.org/rss/1.0/");
			rootEle2.setAttribute("xmlns:dc", "http://purl.org/dc/elements/1.1/");
			rootEle2.setAttribute("xmlns:georss", "http://www.georss.org/georss");			
			//dom.appendChild(rootEle);
			dom2.appendChild(rootEle2);			
			printToFile2(dom2);
			comment = dom2.createComment("This is comment");
			rootEle2.appendChild(comment);
	}

	public void createDocument() {

		// factory instancia lekerese
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
			// builder instancia lekerese
			DocumentBuilder db = dbf.newDocumentBuilder();

			// DOM objektum letrehozas
			dom = db.newDocument();
			dom2=db.newDocument();
			
		} catch (ParserConfigurationException pce) {
			System.out.println("Error while trying to instantiate DocumentBuilder "	+ pce);
			System.exit(1);
		}

	}

	private void printToFile(Document dom) {

		try {
			DOMSource ds = new DOMSource(dom);
			File f = new File(
					"C:/Users/Peti/Desktop/workspace/bandi.osgi.webapp/web/gpsData.xml");
			//f.delete();
			StreamResult sr = new StreamResult(f);
			Transformer transformer = TransformerFactory.newInstance().newTransformer();
			transformer.transform(ds, sr);
			f.createNewFile();

		} catch (Exception ie) {
			ie.printStackTrace();
		}
	}
	private void printToFile2(Document dom) {

		try {
			DOMSource ds = new DOMSource(dom);
			File f = new File(
					"C:/Users/Peti/Desktop/workspace/bandi.osgi.webapp/web/offline.xml");
			//f.delete();
			StreamResult sr = new StreamResult(f);
			Transformer transformer = TransformerFactory.newInstance().newTransformer();
			transformer.transform(ds, sr);
			f.createNewFile();

		} catch (Exception ie) {
			ie.printStackTrace();
		}
	}
	
	
	public void updateFile(List<ClientMessage> messages) {
		System.out.println("Started .. ");
		boolean ok=true;
		
		NodeList nl = rootEle.getElementsByTagName("item");
		for (ClientMessage cm : messages) {
			
			User u = cm.getUser();
			Device d = cm.getDevice();
			DeviceDAOImpl asd = new DeviceDAOImpl();
			GpsGGAMessage g = cm.getGpsGGAMessage();
			for(int x=0;x<nl.getLength();x++){
				NodeList subChildNodes = nl.item(x).getChildNodes();
				try {
					Long id=d.getDevice_id();
					if (subChildNodes.item(0).getTextContent().equals(id.toString())) {
						String htmlCdata = "<b>Position:</b><br>  <i>Latitude:</i>"
							+ g.getLatitudeFloat() + "<br>  <i>Longitude:</i>"
							+ g.getLongitudeFloat() + "<br>";
						htmlCdata += "<b>Time: </b>" + g.getUtcPosition() + "<br>";
						htmlCdata += "<b>Device: </b>"
							+ d.getDevice_type().getManufacturer() + " "
							+ d.getDevice_type().getModel() + "<br>";
						htmlCdata += "<b>Phone Number: </b>" + d.getPhone_number() + ", "
							+ d.getCarrier();
						
						subChildNodes.item(1).setTextContent(htmlCdata);						
						
						subChildNodes.item(2).setTextContent(cm.getGpsGGAMessage()
								.getLatitudeFloat()
								+ " " + cm.getGpsGGAMessage().getLongitudeFloat());
						ok=false;
						printToFile(dom);
						String str = Float.toString(g.getLatitudeFloat());
						d.setLat(str);
						str = Float.toString(g.getLongitudeFloat());
						d.setLon(str);
						Calendar cal = Calendar.getInstance();
						SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
						d.setTime(sdf.format(cal.getTime()));
						
						asd.updateDevice(d);
						
					}
					} catch (Exception e) {
					}		
				
			}
		}
		           
			
		if (ok){	
		 //create a comment
		  Comment comment = dom.createComment("This is comment");
		  //add in the root element
		  rootEle.appendChild(comment);
	//	NodeList nodes = dom.getElementsByTagName("item");
		for (ClientMessage cm : messages) {
			
			User u = cm.getUser();
			Device d = cm.getDevice();
			GpsGGAMessage g = cm.getGpsGGAMessage();
			Element gpsData = dom.createElement("item");
			Element data = dom.createElement("title");
			Long id=d.getDevice_id();
			data.appendChild(dom.createTextNode(id.toString()));
			gpsData.appendChild(data);
			data = dom.createElement("description");
			// build short html description
			String htmlCdata = "<b>Position:</b><br>  <i>Latitude:</i>"
					+ g.getLatitudeFloat() + "<br>  <i>Longitude:</i>"
					+ g.getLongitudeFloat() + "<br>";
			htmlCdata += "<b>Time: </b>" + g.getUtcPosition() + "<br>";
			htmlCdata += "<b>Device: </b>"
					+ d.getDevice_type().getManufacturer() + " "
					+ d.getDevice_type().getModel() + "<br>";
			htmlCdata += "<b>Phone Number: </b>" + d.getPhone_number() + ", "
					+ d.getCarrier();
			data.appendChild(dom.createCDATASection(htmlCdata));
			gpsData.appendChild(data);
			data = dom.createElement("georss:point");
			data.appendChild(dom.createTextNode(cm.getGpsGGAMessage()
					.getLatitudeFloat()
					+ " " + cm.getGpsGGAMessage().getLongitudeFloat()));
			gpsData.appendChild(data);
			data = dom.createElement("dc:creator");
			data.appendChild(dom.createTextNode("TrackingService"));
			gpsData.appendChild(data);
			data = dom.createElement("dc:date");
			data.appendChild(dom.createTextNode("2006-06-08T17:35:01.942452+00:00"));
			gpsData.appendChild(data);
			//rootEle.appendChild(gpsData);
			//dom.appendChild(gpsData);
			rootEle.insertBefore(gpsData, comment);
		}
		
		//dom.appendChild(rootEle);
		printToFile(dom);
		System.out.println("File generated successfully.");
	}
	}
	
	public void offline(){
	
		 DateFormat formatter ; 
		 Date date = null ; 
		  formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		DeviceDAOImpl asd = new DeviceDAOImpl();
		List<Device> list =asd.getAllDevices();
		for(Device d : list){
			try {
				date = (Date)formatter.parse(d.getTime());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			
			Calendar cal=Calendar.getInstance();
			cal.setTime(date);
			Calendar now = Calendar.getInstance();
			now.add(Calendar.SECOND,-10);
			if(now.getTime().after(cal.getTime())){
				NodeList nl = rootEle.getElementsByTagName("item");
				for(int x=0;x<nl.getLength();x++){	
					NodeList subChildNodes = nl.item(x).getChildNodes();
					try {
						Long id=d.getDevice_id();
						if (subChildNodes.item(0).getTextContent().equals(id.toString())) {
							
							 rootEle.removeChild(nl.item(x));
							 printToFile(dom);
							 //-------------------
							 
							    Element gpsData = dom2.createElement("item");
								Element data = dom2.createElement("title");
								
								data.appendChild(dom2.createTextNode(id.toString()));
								gpsData.appendChild(data);
								data = dom2.createElement("description");
								// build short html description
								String htmlCdata = "<b>Position:</b><br>  <i>Latitude:</i>"
										+ d.getLat() + "<br>  <i>Longitude:</i>"
										+ d.getLon() + "<br>";
								htmlCdata += "<b>Time: </b>" + d.getTime() + "<br>";
								htmlCdata += "<b>Device: </b>"
										+ d.getDevice_type().getManufacturer() + " "
										+ d.getDevice_type().getModel() + "<br>";
								htmlCdata += "<b>Phone Number: </b>" + d.getPhone_number() + ", "
										+ d.getCarrier();
								data.appendChild(dom2.createCDATASection(htmlCdata));
								gpsData.appendChild(data);
								data = dom2.createElement("georss:point");
								data.appendChild(dom2.createTextNode(d.getLat()+ " " + d.getLon()));
								gpsData.appendChild(data);
								data = dom2.createElement("dc:creator");
								data.appendChild(dom2.createTextNode("TrackingService"));
								gpsData.appendChild(data);
								data = dom2.createElement("dc:date");
								data.appendChild(dom2.createTextNode(d.getTime()));
								gpsData.appendChild(data);								
								rootEle2.insertBefore(gpsData, comment);
								printToFile2(dom2);							 
						
						}
						} catch (Exception e) {
						}		
				}
			}
		}
	}
	
}
